package com.toutou.base.util

import android.app.Activity
import android.app.Dialog
import android.view.Gravity
import android.view.LayoutInflater
import android.view.WindowManager
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import com.toutou.base.R


private var loadingDialogFragment: Dialog? = null


fun showLoadingExt(message: String){
    ActivitiesManager.topActivity()?.let {
        if (!it.isFinishing && !it.isDestroyed) {
            if (loadingDialogFragment == null) {
                loadingDialogFragment = Dialog(it, R.style.loading_dialog)?.apply {
                    setCancelable(true)
                    setCanceledOnTouchOutside(false)
                    val view = LayoutInflater.from(it).inflate(R.layout.base_layout_progress_dialog_view, null)
                    setContentView(view)
                    window?.setBackgroundDrawableResource(android.R.color.transparent)
                    this.findViewById<TextView>(R.id.loading_tips).text = message
                    val layoutParams = view!!.layoutParams
                    layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT  // 设置宽度为屏幕宽度的80%
                    layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT
                    window?.setGravity(Gravity.CENTER)
                }
            }
            loadingDialogFragment?.show()
        }
    }
}
/**
 * 关闭等待框
 */
fun Activity.dismissLoadingExt() {
    loadingDialogFragment?.dismiss()
    loadingDialogFragment = null
}

/**
 * 关闭等待框
 */
fun Fragment.dismissLoadingExt() {
    loadingDialogFragment?.dismiss()
    loadingDialogFragment = null
}

fun ViewModel.dismissLoadingExt(){
    loadingDialogFragment?.dismiss()
    loadingDialogFragment = null
}
